var express = require('express')
var jwt = require('jsonwebtoken')
const adminsmodel = require('../model/adminsModel')
var router = express.Router()

router.post('/login', async (req, res) => {
    let result = await adminsmodel.findOne(req.body)
    if (result) {
        const token = jwt.sign(
            {
                adminsName: result.adminsName
            },
            'giles',
            { expiresIn: '12h' }

        )
        res.send({ code: 1, msg: '登录成功', token: 'Bearer ' + token })
    } else {
        res.send({ code: 0, msg: '登录失败' })
    }
})
router.put('/update', async (req, res) => {
    let { modifiedCount } = await adminsmodel.updateOne({ _id: req.body._id }, req.body)
    if (modifiedCount) {
        res.send({
            code: 1,
            message: '修改成功',

        })
    }
    else {
        res.send({
            code: 0,
            message: '修改失败',

        })
    }
})
router.get('/getAdmin/:_id', async (req, res) => {
    let result = await adminsmodel.findById(req.params._id)
    if (result) {
        res.send(
            {
                code: 1,
                message: '查询成功',
                data: result
            }
        )
    } else {
        res.send(
            {
                code: 0,
                message: '查询失败'
            }
        )
    }
})
router.get('/getByname', async (req, res) => {

    let result = await adminsmodel.find({ adminsName: { $regex: req.query.adminsName } })

    console.log(result);


})
router.put('/frozen', async (req, res) => {
    let { modifiedCount } = await adminsmodel.updateOne({ _id: req.body._id },req.body)
    if (modifiedCount) {
        res.send({
            code: 1,
            message: '修改成功',

        })
    }
    else {
        res.send({
            code: 0,
            message: '修改失败',

        })
    }
})
router.post('/addadmins',async(req,res)=>{
    let admins={
        adminsName:req.body.adminsName,
        adminsPassword:req.body.adminsPassword,
        frozen:req.body.frozen,
        adminsState:~~req.body.adminsState,
        delete:req.body.delete,
    }
    try{
        const result=await adminsmodel.create(admins)
        if(result){
            res.send({
                code:1,
                message:'增加成功'
            })
        }
}catch(err){
        res.send({
            code:0,
            message:'增加失败'
        })
}
})








module.exports = router